<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.proCode"
        size="small"
        placeholder="商品编码"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <p style="display:inline-block;margin-left:2%">商品类型：</p>
      <el-select
          size="small"
          placeholder="全部"
          clearable
          class="filter-item"
          style="width: 130px"
          v-model="deptValue"
        >
          <el-option v-for="item in deps" :key="item.id" :label="item.name" :value="item.catId"/>
        </el-select>
      <el-input
        v-model="listQuery.goodsBrand"
        size="small"
        placeholder="商品品牌"
        style="width: 200px;margin-left:3%"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.infoName"
        size="small"
        placeholder="商品名称"
        style="width: 200px;margin-left:3%"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        size="small"
        class="filter-item"
        type="success"
        icon="el-icon-search"
        style="margin-left:3%"
        @click="handleFilter"
      >
        搜索
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      size="small"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column
        :class-name="getSortClass('id')"
        label="ID"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品编码" width="130px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.proCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品" min-width="200px" align="center">
        <template slot-scope="scope" style="display:flex; justify-content:space-around">
          <div style="display:flex; justify-content:space-around;width:100%;height:100%">
            <div style="width:40%;height:100%">
              <img style="width:70%;height:70%" @click="showBig(scope.row)" :src="scope.row.imageUrl">
            </div>
            <el-dialog append-to-body :visible.sync="dialogible">
              <img width="100%" :src="dialogImage" alt="">
            </el-dialog>
            <div style="width:40%;height:100%;display:flex;flex-direction:column;align-items:center">
              <p style="display:block;width:100%; height: 50%">{{scope.row.infoName}}</p>
              <p style="display:block;width:100%; height: 50%">{{scope.row.title}}</p>
            </div>       
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品品牌" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.goodsBrand }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品类型" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.catName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购价" width="200" align="center">
        <template slot-scope="scope">
          <span style="display:inline-block;width:100%" v-for="(item,index) in scope.row.proPriceVosList" :key="index">{{item.proTitle}}&nbsp;&nbsp;&nbsp;：&nbsp;&nbsp;&nbsp;￥{{ item.proPurchansePrice }}</span>
          <!-- <span>{{this.moneyList}}</span> -->
        </template>
      </el-table-column>
      <el-table-column label="市场价" width="150" align="center">
        <template slot-scope="scope">
          <span style="display:inline-block;width:100%">￥{{scope.row.proMarketPrices }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售价" width="150" align="center">
        <template slot-scope="scope">
          <span style="display:inline-block;width:100%" v-for="(item,index) in scope.row.proPriceVosList" :key="index">{{item.proTitle}}&nbsp;&nbsp;&nbsp;：&nbsp;&nbsp;&nbsp;￥{{ item.proSellPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分佣设置" width="350px" align="center">
        <template slot-scope="scope">
          <ul style="list-style:none;padding:0;"  v-for="(item,index) in scope.row.proLimitConditionList" :key="index">
            <li style="float:left;width:25%">{{moneyList.length===0?'':moneyList[index].proTitle+' ： '}}</li>
            <li style="float:left;width:25%">县域：￥{{item.countryTeam}}</li>
            <li style="float:left;width:25%">乡镇：￥{{item.villiangeTeam}}</li>
            <li style="float:left;width:25%">掌柜：￥{{item.shopkeeper}}</li>
          </ul>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"  
        width="100px"
        class-name="small-padding fixed-width"
      > 
        <template slot-scope="{ row }">
          <el-button
            size="small"
            align="center"
            type="primary"
            v-if="moneyList.length!==0"
            @click="handleUpdate(row)"
          >
            设置
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog
      @close="loadPage"
      :close-on-click-modal="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      append-to-body
    >
      <div v-for="(item,index) in proLimitList" :key="index">
        <span style="font-size:18px;font-weight:bold">{{moneyList[index].proTitle}}:</span>
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="temp"
          label-position="left"
          label-width="150px"
          style="width: 400px; margin-left:20%;margin-bottom:5%">
          <el-form-item label="佣金设置：">
            <span>固定值</span>
          </el-form-item>
          <el-form-item label="县域团队：">
            <el-input placeholder="请输入金额" v-model="item.countryTeam" />
          </el-form-item>
          <el-form-item label="乡镇协理：">
            <el-input placeholder="请输入金额" v-model="item.villiangeTeam" />
          </el-form-item>
          <el-form-item label="易掌柜/联络员：">
            <el-input placeholder="请输入金额" v-model="item.shopkeeper" />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="updateData()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { commissionList,updataCommission,getSearchList } from '@/api/commission'// 异步请求 delLly
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // 分页插件

const calendarTypeOptions = [
  { key: 0, display_name: '无效' },
  { key: 1, display_name: '正常' },
  { key: 2, display_name: '锁定' }
]
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  inject:["reload"],
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      dialogible:false,
      dialogImage:'',
      deptValue:'',
      tableKey: 0,
      list: null,
      moneyList:[],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        proCode: '',
        goodsBrand: '',
        infoName:'',
        sort: '+id'
      },
      deps:[],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        proLimitConditionList:null
      },
      proLimitList:[],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      dialogPvVisible: false,
      outerVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      liaUser: null,
    }
  },
  created() {
    this.getList()
    this.getSearch()
  },
  methods: {
    loadPage(){
      // setTimeout(function(){  //使用  setTimeout（）方法设定定时800毫秒
      //   window.location.reload();//页面刷新
      // },800);
      this.reload()
    },
    showBig(row){
      console.log(row)
      this.dialogible=true
      this.dialogImage=row.imageUrl
    },
    getSearch(){
      getSearchList().then(res=>{
        this.deps=res.data
        console.log(this.deps)
      })
    },
    getList() {
      this.listLoading = true
      var params = {
        // pageConvert: true,
        pageNum: this.listQuery.pageNum,
        pageSize: this.listQuery.pageSize,
        goodsBrand: this.listQuery.goodsBrand,
        proCode: this.listQuery.proCode,
        infoName :this.listQuery.infoName,
        catId: this.deptValue
      }
      commissionList(params).then(response => {
        this.list = response.content
        this.list.forEach((item)=>{
          console.log(item.proPriceVosList)
          this.temp.proLimitConditionList=item.proLimitConditionList
          this.moneyList=item.proPriceVosList
        })
        console.log(this.moneyList)
        // console.log(this.list)
        this.total = response.totalElements
        // console.log(this.total)
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined
      }
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      for(var i=0; i<this.temp.proLimitConditionList.length;i++){
          this.proLimitList.push(this.temp.proLimitConditionList[i])
        }
        console.log(this.proLimitList)
      
      this.dialogFormVisible = true
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      // })
    },
    updateData() {
      // this.$refs['dataForm'].validate((valid) => {
      //   if (valid) {
        const tempData = this.proLimitList
        console.log(tempData)
        var params={
          proLimitConditionList:tempData
        }
        updataCommission(params).then(() => {
          for (const v of this.list) {
            if (v.id === this.temp.id) {
              const index = this.list.indexOf(v)
              this.list.splice(index, 1, this.temp)
              break
            }
          }
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 2000
          })
          // setTimeout(function(){  //使用  setTimeout（）方法设定定时800毫秒
          //   window.location.reload();//页面刷新
          // },800);
          this.reload()
        })
      //   }
      // })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    }
  }
}
</script>